package com.basic.backend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basic.backend.annotation.AuthCheck;
import com.basic.backend.common.BaseResponse;
import com.basic.backend.common.ErrorCode;
import com.basic.backend.common.ResultUtils;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.model.dto.Images.ImageAnalysisDTO;
import com.basic.backend.model.dto.articles.ArticleQueryRequest;
import com.basic.backend.model.entity.AnalysisResult;
import com.basic.backend.model.entity.ArticleVideos;
import com.basic.backend.model.vo.AnalysisResultVO;
import com.basic.backend.model.vo.UserVO;
import com.basic.backend.model.vo.VideoVO;
import com.basic.backend.service.AnalysisService;
import com.basic.backend.service.ArticleImagesService;
import com.basic.backend.service.ArticleVideosService;
import com.basic.backend.service.UserService;
import com.basic.backend.service.impl.MessageProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/video")
@Api(tags = "视频管理")
@Slf4j
public class ArticleVideoController {

    @Resource
    private ArticleVideosService videoService;

    @Resource
    private UserService userService;

    @Resource
    private AnalysisService analysisService;

    @Resource
    private ArticleImagesService articleImagesService;

    @Resource
    private MessageProducer messageProducer;

    @GetMapping("/analysis")
    @ApiOperation(value = "获取视频分析结果", notes = "返回结构化热词列表")
    public BaseResponse<AnalysisResultVO> getAnalysisResult(
            @RequestParam  Long articleId) {

        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频ID不合法");
        }

        // 查询原始数据
        AnalysisResult entity = analysisService.getOne(
                new LambdaQueryWrapper<AnalysisResult>()
                        .eq(AnalysisResult::getArticleId, articleId)
                        .last("LIMIT 1")
        );

        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "分析结果不存在");
        }

        // 转换VO
        AnalysisResultVO vo = new AnalysisResultVO();
        BeanUtils.copyProperties(entity, vo);
        // 用户信息处理（添加空值防御）
        Long userId = videoService.getById(vo.getArticleId()).getUserId();
        if (userId == null) {
            log.warn("视频ID: {} 缺少用户ID", articleId);
            vo.setAuthor("未知作者");
        } else {
            UserVO userVO = userService.getUserVO(userId);
            if (userVO != null && userVO.getUserName() != null) {
                vo.setAuthor(userVO.getUserName());
            } else {
                log.warn("用户ID: {} 信息不存在", userId);
                vo.setAuthor("未知作者");
            }
        }

        // 字数统计（防御空内容）
        String content = videoService.getById(articleId).getContent();
        vo.setWordCount(content != null ? content.length() : 0);

        vo.setHotWords(convertHotWords(entity.getHotWords()));
        return ResultUtils.success(vo, "查询成功");
    }

    // JSON字符串转列表
    private List<AnalysisResultVO.HotWord> convertHotWords(String hotWordsJson) {
        try {
            return JSON.parseArray(hotWordsJson, AnalysisResultVO.HotWord.class);
        } catch (JSONException e) {
            log.error("热词解析失败 JSON: {}", hotWordsJson, e);
            return Collections.emptyList();
        }
    }

    @PostMapping("/video")
    @ApiOperation(value = "创建视频（COS存储版）")
    public BaseResponse<Boolean> createVideoArticle(
            @RequestParam("video") MultipartFile videoFile,
            @RequestParam String title,
            @RequestParam String content,
            HttpServletRequest request) {

        // 基础校验
        if (videoFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频文件不能为空");
        }
        if (!videoFile.getContentType().startsWith("video/")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频文件格式不正确");
        }
        // 提交异步处理
        long userId = userService.getLoginUser(request).getId();
        boolean result = videoService.processVideoArticle(videoFile, title, content,userId);
        HashMap<Object, Object> body = new HashMap<>();
        body.put("message", "视频处理已开始");
        body.put("trackingId", UUID.randomUUID().toString());
        return ResultUtils.success(result,"");
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除视频", notes = "根据视频ID删除视频")
    public BaseResponse<Boolean> deleteArticle(@RequestParam("id") Long articleId,
                                               HttpServletRequest request) {
        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频ID不合法");
        }

        // 获取当前登录用户
        Long userId = userService.getUserIdByToken(request);
        // 删除视频
        boolean result = videoService.removeById(articleId);
        return result ? ResultUtils.success(true, "删除成功") : ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
    }

    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除视频")
    @AuthCheck(mustRole = "user")
    public BaseResponse<Boolean> deleteBatch(@RequestBody List<Long> articleIds, HttpServletRequest request) {
        if (articleIds == null || articleIds.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        // 获取当前登录用户
        Long userId = userService.getUserIdByToken(request);
        if (!userService.isAdmin(request) && !userId.equals(userService.getLoginUser(request).getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 删除文章
        boolean result = videoService.removeByIds(articleIds);
        return result ? ResultUtils.success(true, "删除成功") : ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
    }

    @PostMapping("/info")
    @ApiOperation(value = "获取视频详情", notes = "根据视频ID获取视频详情")
    public BaseResponse<VideoVO> getArticleInfo(@RequestParam Long articleId, HttpServletRequest request) {
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频ID不合法");
        }
        ArticleVideos videos = videoService.getById(articleId);
        if (videos == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "视频不存在");
        }
        VideoVO articleVO = new VideoVO();
        BeanUtils.copyProperties(videos, articleVO);
        UserVO author = userService.getUserVO(userService.getById(videos.getUserId()));
        articleVO.setAuthor(author);
        articleVO.setImages(Arrays.asList(videos.getImages().split(",")));
        articleVO.setVideoUrl(videos.getVideoUrl());
        return ResultUtils.success(articleVO,"");
    }

    @PostMapping("/page")
    @ApiOperation("视频分页查询")
    public BaseResponse<Page<VideoVO>> getArticlePage(
            @RequestBody ArticleQueryRequest request,
            HttpServletRequest httpRequest) {

        // 权限处理
        Long userId = userService.getUserIdByToken(httpRequest);
        if (!userService.isAdmin(httpRequest)) {
            request.setUserId(userId);
        }
        // 分页查询
        Page<VideoVO> result = videoService.getArticleImagesPage(request,httpRequest);
        return ResultUtils.success(result, "");
    }

    @PostMapping("/update")
    @ApiOperation("更新视频")
    public BaseResponse<String> updateArticle(
            @RequestParam Long id,
            @RequestPart(value = "video", required = false) MultipartFile videoFile,
            @RequestParam String title,
            @RequestParam String content) {

        // 带文件上传的POST更新
        if (videoFile != null && !videoFile.isEmpty()) {
            videoService.updateVideoArticle(videoFile, title, content, id);
            return new BaseResponse<>(0, "带视频更新任务已提交");
        }

        // 无文件纯内容更新
        ArticleVideos article = new ArticleVideos();
        article.setArticleId(id);
        article.setTitle(title);
        article.setContent(content);
        videoService.updateById(article);
        ImageAnalysisDTO analysisDTO = new ImageAnalysisDTO();
        ArticleVideos videos = videoService.getById(id);
        BeanUtil.copyProperties(videos, analysisDTO);
        analysisDTO.setPublishTime(LocalDateTime.now().toString());
        messageProducer.sendImageAnalysisTask(analysisDTO);
        return new BaseResponse<>(0, "内容更新成功");
    }


}
